﻿using Huasky.MyWrod.Common.Util;
using Huasky.MyWrod.Core.Annotations;
using Huasky.MyWrod.Core.BackgroundTask;
using System.Reflection;

namespace Huasky.MyWrod.Web.Core.Extensions;

public static class HuaskkApiRegisterEx
{
    /// <summary>
    /// 添加Huasky.MyWrod服务
    /// </summary>
    public static void AddHuaskyApiServices(this IServiceCollection services)
    {
        foreach (var (type, attribute) in loadDiInfo<HuaskyApiServiceAttribute>())
        {
            var descriptor = attribute.CreateDescriptor(type);
            services.Add(descriptor);
        }
    }

    /// <summary>
    /// 添加Huasky.MyWrod任务
    /// </summary>
    public static void AddHuaskyApiTasks(this IServiceCollection services)
    {
        //注入的任务
        foreach (var type in DIHelper.GetTypes<HuaskyApiTask>(getAssemblies()))
        {
            if (!typeof(IHostedService).IsAssignableFrom(type))
                throw new InvalidOperationException($"[{type.Name}] 未实现 <IHostedService> 接口");

            var descriptor = new ServiceDescriptor(typeof(IHostedService), type, ServiceLifetime.Singleton);
            services.Add(descriptor);
        }
    }

    static (Type, T)[] loadDiInfo<T>() where T : Attribute
    {
        return DIHelper.LoadDiInfo<T>(getAssemblies());
    }


    static Assembly[] getAssemblies()
    {
        //todo assembly后续改成所依赖的程序集
        return DIHelper.GetAssemblies();
    }

}
